<?php
declare (strict_types=1);

namespace app\common\model;

class Address extends Base
{
    protected $name = 'user_address';

    public function p()
    {
        return $this->hasOne(Area::class, 'code', 'province')->field('id,code,province as title');
    }

    public function c()
    {
        return $this->hasOne(Area::class, 'code', 'city')->field('id,code,city as title');
    }

    public function d()
    {
        return $this->hasOne(Area::class, 'code', 'district')->field('id,code,district as title');
    }

    public static function add($param, $user): array
    {
        try {
            if (isset($param['default']) && $param['default'] == 1) {
                parent::update(['default' => 0], ['uid' => $user->id]);
            }
            if (isset($param['id']) && $param['id']) {
                parent::update($param);
                $msg = '已修改';
            } else {
                $param['uid'] = $user->id;
                parent::create($param);
                $msg = '已添加';
            }
            return ['code' => 1, 'msg' => $msg];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function edit($id, $user): array
    {
        try {
            $info = parent::where('id', $id)->find();
            if (empty($info) || $info->uid != $user->id) {
                return ['code' => -1, 'msg' => '加载失败，记录不存在'];
            }
            $info->is_del = 1;
            $info->save();
            return ['code' => 1, 'msg' => '已删除'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function default($id, $user): array
    {
        try {
            $info = parent::where('id', $id)->find();
            if (empty($info) || $info->uid != $user->id) {
                return ['code' => -1, 'msg' => '加载失败，记录不存在'];
            }
            parent::update(['default' => 0], ['uid' => $user->id]);
            $info->default = 1;
            $info->save();
            return ['code' => 1, 'msg' => '已设为默认地址'];

        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    public static function getDefault($uid)
    {
        try {
            $info = parent::with(['p', 'c', 'd'])->where(['uid' => $uid, 'is_del' => 0, 'default' => 1])
                ->withoutField('is_del,create_time,update_time,uid,town')->find();
            if ($info) return $info;

            $info = parent::with(['p', 'c', 'd'])->where(['uid' => $uid, 'is_del' => 0])
                ->withoutField('is_del,create_time,update_time,uid,town')->order('update_time', 'desc')->find();
            if ($info) return $info;

            return "";
        } catch (\Exception $e) {
            return "";
        }
    }
}